import router from "../router/index.js";

/**
 * 动态路由解析工具类
 */
export const DynamicRouteUtil = {
    // 解析路由菜单
    parseRouteMenu: (menuList) => {
        const routeMenuList = [];
        if (!menuList || menuList.length === 0) {
            return routeMenuList;
        }
        // 获取 pages 目录下的所有 .vue 文件
        const pages = import.meta.glob('../pages/**/*.vue', {eager: true});
        // 遍历后端返回的菜单数据
        menuList.forEach(menu => {
            // 获取解析之后的路由
            const route = DynamicRouteUtil.handleRoute(menu, pages);
            // 添加到动态路由里面
            if (Object.keys(route).length > 0) {
                router.addRoute(route);
                routeMenuList.push(route);
            }
        });
        return routeMenuList;
    }, // 处理路由
    handleRoute: (menu, pages) => {
        const route = {
            path: menu.path === '#' ? '' : menu.path, name: menu.name, hidden: menu.hidden, meta: {
                title: menu.meta?.title, icon: menu.meta?.icon
            }, children: []
        };
        // todo 这里根据后端返回的结果来判断
        // 如果组件值是 # 号，则添加 layout 布局组件
        if (!menu['component'] || menu['component'] === '#') {
            route.component = DynamicRouteUtil.loadComponent('/main/index', pages);
        } else {
            // 加载组件
            route.component = DynamicRouteUtil.loadComponent(menu['component'], pages);
        }
        // 是否存在子菜单
        if (menu.children && menu.children.length > 0) {
            menu.children.forEach(childMenu => {
                // 递归处理子菜单数据
                const childRoute = DynamicRouteUtil.handleRoute(childMenu, pages);
                if (Object.keys(childRoute).length > 0) {
                    route.children.push(childRoute);
                }
            });
        }
        return route;
    }, // 加载组件对象
    loadComponent: (component, pages) => {
        console.log('+++++++++',component,pages)
        if (component.startsWith('/')) {
            component = component.substring(1);
        }
        if (component.endsWith('/')) {
            component = component.substring(0, component.length - 1);
        }
        // 返回获取到组件对象
        return pages[`../components/${component}.vue`];
    }
};